package com.crazymaker.cloud.nacos.demo.sentinel.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.crazymaker.cloud.nacos.demo.sentinel.handler.CustomerBlockHandler;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/flowControllDemo")
@Api(tags = "流控演示")
@Slf4j
public class FlowControllDemoController
{
    @GetMapping("/test1")
    public String test1()
    {
        log.info(Thread.currentThread().getName() + "\t" + "...test1");
        return "-------hello baby，i am test1";
    }

    @GetMapping("/test1_related")
    public String test1_related()
    {
        log.info(Thread.currentThread().getName() + "\t" + "...test1_related");
        return "-------hello baby，i am test1_related";
    }

    @GetMapping("/test2")
    public String test2()
    {
        int num = 1 / 0;
        log.info(Thread.currentThread().getName() + "\t" + "...test2");
        return "------测试异常数，i am test2";
    }


    @GetMapping("/test3")
    @SentinelResource(value = "byUrl")
    public String test3()
    {
        log.info(Thread.currentThread().getName() + "\t" + "...test3");
        return "------按url限流测试OK，i am test3";
    }

    @GetMapping("/test4")
    @SentinelResource(value = "byHotKeyUserId",
            blockHandler = "userAccessError")
    public String test4(@RequestParam(value = "userId", required = false) String userId,
                        @RequestParam(value = "goodId", required = false) String goodId)
    {
        log.info(Thread.currentThread().getName() + "\t" + "...test4");
        return "-----------by HotKey： UserId";
    }

    public String userAccessError(String userId, String goodId, BlockException exception)
    {
        return "------userAccessError，i am from  test4";
    }


    @GetMapping("/test5")
    @SentinelResource(value = "byHotKeyUserId",
            blockHandlerClass = CustomerBlockHandler.class,
            blockHandler = "userAccessError")
    public String test5(@RequestParam(value = "userId", required = false) String userId,
                        @RequestParam(value = "goodId", required = false) String goodId)
    {
        log.info(Thread.currentThread().getName() + "\t" + "...test4");
        return "-----------by HotKey： UserId";
    }
}
